package com.video.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.video.dao.TagVlogMapper;
import com.video.dao.TagsMapper;
import com.video.dao.VlogsMapper;
import com.video.entity.TagVlog;
import com.video.entity.Tags;
import com.video.entity.Vlogs;
import com.video.exception.VideoException;
import com.video.result.AppHttpCodeEnum;
import com.video.result.ResultVO;
import com.video.service.TagsService;
import com.video.vo.PageVo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * (Tags)表服务实现类
 *
 * @author baoshuai
 * @since 2022/12/14
 */
@Service("tagsService")
public class TagsServiceImpl extends ServiceImpl<TagsMapper, Tags> implements TagsService {

    @Resource
    private TagVlogMapper tagVlogMapper;

    @Resource
    private VlogsMapper vlogsMapper;

    @Override
    public ResultVO hotTags() {
        List<Tags> hotTags = baseMapper.selectHotTags();
        return ResultVO.success(hotTags);
    }

    @Override
    public ResultVO pageVlogsByTagId(Long tagId, Integer pageNum, Integer pageSize) {
        if (Objects.isNull(getById(tagId))) {
            throw new VideoException(AppHttpCodeEnum.TAG_NOT_EXIST);
        }
        Page<Vlogs> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<TagVlog> tagVlogLambdaQueryWrapper = new LambdaQueryWrapper<>();
        tagVlogLambdaQueryWrapper.eq(TagVlog::getTagId, tagId);
        List<Long> vlogIds = tagVlogMapper.selectList(tagVlogLambdaQueryWrapper).stream()
                .map(TagVlog::getVlogId).collect(Collectors.toList());


        if (vlogIds.size() <= 0) {
            return ResultVO.success(new PageVo(0L, new ArrayList()));
        }

        LambdaQueryWrapper<Vlogs> vlogsLambdaQueryWrapper = new LambdaQueryWrapper<>();
        vlogsLambdaQueryWrapper.in(Vlogs::getId, vlogIds);
        vlogsMapper.selectPage(page, vlogsLambdaQueryWrapper);

        PageVo pageVo = new PageVo(page.getTotal(), page.getRecords());

        return ResultVO.success(pageVo);
    }

    @Override
    public ResultVO selectTagsTop6() {
        List<Tags> tagsList = baseMapper.selectTagsTop6();
        return ResultVO.success(tagsList);
    }

    @Override
    public ResultVO getTagsByKeyword(String keyword) {
        LambdaQueryWrapper<Tags> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasText(keyword), Tags::getTag, keyword);
        List<Tags> tagsList = list(queryWrapper);
        return ResultVO.success(tagsList);
    }

}

